package com.sdx.interceptors;

import com.sdx.exception.SdxError;
import com.sdx.exception.SdxException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** 攻击过滤
 * @ClassName WordFilterInterceptor
 * @Description: No Description
 * @author: tanbaocai
 * @date: 2020/4/15 10:03
 */
public class XSSInterceptor implements HandlerInterceptor {
	private static final Pattern XSSWORDS = Pattern.compile(".*([<>'\\\" \t]|&#)+.*");
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Iterator<String[]> paramValues = request.getParameterMap().values().iterator();
		while(paramValues.hasNext()) {
			String[] values = paramValues.next();
			for (int i = 0; i < values.length; i++) {
				Matcher matcher = XSSWORDS.matcher(values[i]);
				if (matcher.matches()) {
					throw new SdxException(SdxError.HTTP_ERROR,"输入非法字符");
				}
			}
		}
		return true;
	}
	public static void main(String[] args) {
		Matcher matcher = XSSWORDS.matcher("lsdkjgal&#ert");
		System.out.println(matcher.matches());
	}
}
